<template>
  <div class='search-sort'>
    <div class="sort">
      <a :class="{active:sortParams.sortField===null}" @click="changSort(null)" href="javascript:;">默认排序</a>
      <a :class="{active:sortParams.sortField==='publishTime'}" @click="changSort('publishTime')" href="javascript:;">最新商品</a>
      <a :class="{active:sortParams.sortField==='orderNum'}" @click="changSort('orderNum')" href="javascript:;">最高人气</a>
      <a :class="{active:sortParams.sortField==='evaluateNum'}" @click="changSort('evaluateNum')" href="javascript:;">评论最多</a>
      <a @click="changSort('price')" href="javascript:;">
        价格排序
        <i class="arrow up " :class="{active:sortParams.sortMethod==='asc'}" />
        <i class="arrow down" :class="{active:sortParams.sortMethod==='desc'}" />
      </a>
    </div>
  </div>
</template>


<script>
import { reactive } from 'vue'
import { onBeforeRouteUpdate } from 'vue-router'
export default {
  name: 'SubSort',

  emits: ['change-sort'],
  setup(props, { emit }) {
    // const isUp = ref(false)
    const sortParams = reactive({
      sortField: null,
      sortMethod: null
    })

    onBeforeRouteUpdate((to, from, next) => {
      sortParams.sortField = null
      sortParams.sortMethod = null
      next()
    })

    const changSort = name => {
      if (name === 'price') {
        // 非第一次点击price
        if (sortParams.sortField !== 'price') {
          sortParams.sortField = name
          sortParams.sortMethod = 'desc'
        } else {
          sortParams.sortMethod = sortParams.sortMethod === 'desc' ? 'asc' : 'desc'
        }
      } else {
        // 当你点击的时已激活的按钮,不做任何事情
        if (sortParams.sortField === name) {
          return
        }

        // 不是点击价格
        sortParams.sortField = name
        sortParams.sortMethod = null
      }
      // 通知父组件,将数据拿过去
      // console.log('fasong1shujv1')
      emit('change-sort', sortParams)
    }

    return { changSort, sortParams }
  }
}
</script>


<style scoped lang='less'>
@xtxColor: var(--xtx-color);
.search-sort {
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .sort {
    display: flex;
    a {
      height: 30px;
      line-height: 28px;
      border: 1px solid #e4e4e4;
      padding: 0 20px;
      margin-right: 20px;
      color: #999;
      border-radius: 2px;
      position: relative;
      transition: all 0.3s;
      &.active {
        background: @xtxColor;
        border-color: @xtxColor;
        color: #fff;
      }
      .arrow {
        position: absolute;
        border: 5px solid transparent;
        right: 8px;
        &.up {
          top: 3px;
          border-bottom-color: #bbb;
          &.active {
            border-bottom-color: @xtxColor;
          }
        }
        &.down {
          top: 15px;
          border-top-color: #bbb;
          &.active {
            border-top-color: @xtxColor;
          }
        }
      }
    }
  }
}
</style>